import React, { useEffect, useState } from 'react';
import { Table, Space, Modal, message, Checkbox, Button } from 'antd';
import axios from 'axios';

const PermissionView = () => {
  const [permissions, setPermissions] = useState([]);
  const [allRoles, setAllRoles] = useState([]);
  const [permissionRoles, setPermissionRoles] = useState({});
  const [selectedPermissionsIds, setSelectedPermissionsIds] = useState([51, 52, 53, 54, 55, 56, 57, 58, 59, 60]); // 指定的权限ID数组

  useEffect(() => {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    const token = currentUser?.token;
    if (token) {
      axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
      console.log('设置 Authorization 头:', `Bearer ${token}`);
    } else {
      console.error('未在 currentUser 中找到 token');
    }
    fetchPermissionsWithRoles();
    fetchAllRoles();
  }, []);

  // 获取所有角色信息
  const fetchAllRoles = async () => {
    try {
      const response = await axios.get(`http://localhost:8080/api/roles/get-all-roles`);
      if (response.status === 200) {
        setAllRoles(response.data);
      } else {
        message.error('获取角色信息失败，请稍后再试！');
      }
    } catch (error) {
      console.error('获取角色信息失败:', error);
      message.error('获取角色信息失败，请稍后再试！');
    }
  };

  // 获取指定权限及其关联的角色
  const fetchPermissionsWithRoles = async () => {
    try {
      const response = await axios.post(`http://localhost:8080/api/get-permissions-with-roles`, selectedPermissionsIds);
      if (response.status === 200) {
        setPermissions(response.data.permissions);

        // 构建 permissionRoles 对象
        const permissionRolesMap = {};
        response.data.permissions.forEach(permission => {
          permissionRolesMap[permission.permissionId] = permission.roleIds || [];
        });
        setPermissionRoles(permissionRolesMap);
      } else {
        message.error('获取权限信息失败，请稍后再试！');
      }
    } catch (error) {
      console.error('获取权限信息失败:', error);
      message.error('获取权限信息失败，请稍后再试！');
    }
  };

  // 添加角色到权限
  const handleAddRoleToPermission = async (permissionId, roleId) => {
    try {
      const response = await axios.post(`http://localhost:8080/api/permissions/${permissionId}/add-role`, { roleId });
      if (response.status === 204) {
        message.success('添加角色成功！');
        await fetchPermissionsWithRoles(); // 刷新数据
      } else {
        message.error('添加角色失败，请稍后再试！');
      }

      // 更新本地状态
      const updatedPermissionRoles = { ...permissionRoles };
      updatedPermissionRoles[permissionId] = [...(updatedPermissionRoles[permissionId] || []), roleId];
      setPermissionRoles(updatedPermissionRoles);
    } catch (error) {
      console.error('更新权限失败:', error);
      message.error('添加角色失败，请稍后再试！');
    }
  };

  // 移除角色从权限
  const handleRemoveRoleFromPermission = async (permissionId, roleId) => {
    try {
      const response = await axios.delete(`http://localhost:8080/api/permissions/${permissionId}/remove-role/${roleId}`);
      if (response.status === 204) {
        message.success('移除角色成功！');
        await fetchPermissionsWithRoles(); // 刷新数据
      } else {
        message.error('移除角色失败，请稍后再试！');
      }

      // 更新本地状态
      const updatedPermissionRoles = { ...permissionRoles };
      updatedPermissionRoles[permissionId] = updatedPermissionRoles[permissionId].filter(id => id !== roleId);
      setPermissionRoles(updatedPermissionRoles);
    } catch (error) {
      console.error('更新权限失败:', error);
      message.error('移除角色失败，请稍后再试！');
    }
  };

  const columns = [
    {
      title: '权限ID',
      dataIndex: 'permissionId',
      key: 'permissionId'
    },
    {
      title: '权限名称',
      dataIndex: 'permissionName',
      key: 'permissionName'
    },
    {
      title: '关联角色',
      key: 'roles',
      render: (text, record) => (
          <Space size="middle">
            {allRoles.map(role => (
                <Checkbox
                    key={role.roleId}
                    checked={permissionRoles[record.permissionId]?.includes(role.roleId)}
                    onChange={(e) => e.target.checked ? handleAddRoleToPermission(record.permissionId, role.roleId) : handleRemoveRoleFromPermission(record.permissionId, role.roleId)}
                >
                  {role.roleName}
                </Checkbox>
            ))}
          </Space>
      )
    }
  ];

  return (
      <div>
        <h2>权限管理</h2>
        <Table
            dataSource={permissions}
            columns={columns}
            rowKey="permissionId"
            pagination={false}
            bordered
        />
      </div>
  );
};

export default PermissionView;